/* eslint-disable */
import axios from "axios";
import axiosRetry from "axios-retry";
const request = axios.create({
    baseURL: "",
    timeout: 5000,
    headers: {
        "Content-Type": "application/json",
        originalUrl: window.location.href,
    },
});
axiosRetry(request, {
    retries: 4,
    retryCondition: (err) => {
        console.log("'======'", err);
        return err.message.includes("404");
    },
    shouldResetTimeout: true,
    retryDelay: () => {
        return 0.5 * 1000;
    },
});
request.interceptors.response.use(
    (response) => {
        const data = response.data;
        const { code, redirectUrl = "" } = data;
        // 鉴权功能
        if (code === 40001) {
            window.location.href = redirectUrl;
        } else {
            return response;
        }
    },
    (error) => {
        return error;
    }
);

export function parseSearch(url = "") {
    url = String(url);
    const searchIndex = url.indexOf("?");
    const search = url.slice(searchIndex + 1);
    if (!search) {
        return {};
    }
    const searchStrList = search.split("&");
    const query = searchStrList.reduce((searchObj, item) => {
        const [key, val] = item.split("=");
        return {
            ...searchObj,
            [key]: val,
        };
    }, {});
    return query || {};
}
export const getHiParams = () => {
    const query = window.location.href.split("?")[1];
    const queryObject = parseSearch(query || "");
    const { code } = queryObject;
    return {
        code,
    };
};

const setHead = (config) => {
    let headers = config.headers || {};
    const { code } = getHiParams();
    headers.code = code;
    return {
        ...config,
        headers,
    };
};

const createAPi = (methods) => {
    return async (url, params, config = {}) => {
        const { data } = await request[methods](url, params, setHead(config));
        return JSON.parse(JSON.stringify(data));
    };
};

export const get = async (url, params, config = {}) => {
    const { data } = await request.get(url, {
        params: {
            t: new Date().getTime(),
            ...params,
        },
        ...setHead(config),
    });
    return data;
};

export const post = createAPi("post");
export const put = createAPi("put");
